using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;

namespace dmWS
{
	public class documents : System.Web.UI.Page
	{
		string document;
		KTManage kt;
		protected System.Web.UI.WebControls.DataGrid datagrid;
		protected System.Web.UI.WebControls.DropDownList lista;
		protected System.Web.UI.WebControls.Label titleDoc;
		DataTable dt;
		protected System.Web.UI.WebControls.Button delete;
		protected System.Web.UI.WebControls.Label feedback;
		protected System.Web.UI.WebControls.Button gotoBasket;
		Translation traduzione;

		private void Page_Load(object sender, System.EventArgs e)
		{
			kt = new KTManage();

			traduzione = new Translation(Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"].ToString(), Server.MapPath("sentences.xml"));
			titleDoc.Text = traduzione.getText("titleDoc");

			delete.Text = traduzione.getText("delete");
			delete.Attributes.Add("onclick","javascript:return " + "confirm('"+traduzione.getText("confirmDelete")+"')");
		
			gotoBasket.Text = traduzione.getText("gotoBasket");

			try
			{
				if (!IsPostBack)
					showDocuments();
				if (lista.SelectedItem.Value == "0")
					document = Request.Params["doc"].ToString();
				else
					document = lista.SelectedItem.Value;
				dt = getGrid(document);
				datagrid.DataSource = dt;
				datagrid.DataBind();
			}
			catch (Exception ex) { }

		}

		void showDocuments()
		{
			ListItem primo = new ListItem();
			primo.Text = traduzione.getText("explain");
			primo.Value = "0";
			primo.Selected = true;
			lista.Items.Add(primo);
			

			//mostro tutti i documenti nella cartella enableFramework
			//text: nome della PRIMA versione
			//value: id nella tabella documents
			string folder = System.Configuration.ConfigurationSettings.AppSettings["enabFolder"].ToString();
			/*string query = "select document_content_version.filename, documents.id as idi "+
				" from document_content_version join documents on (document_content_version.document_id = "+
				" documents.id) where document_content_version.id = (select min(id) from "+
				" document_content_version where document_id=idi) and folder_id="+
				folder+" and status_id=1 ";
			*/
			string query = "select document_content_version.filename, documents.id as idi, "+
				"document_metadata_version.name from document_content_version join documents on "+
				"(document_content_version.document_id = documents.id) join document_metadata_version on "+
				"(document_metadata_version.content_version_id = document_content_version.id) "+
				"where document_content_version.id = (select min(id) from document_content_version "+
				"where document_id=documents.id) and folder_id="+folder+" and documents.status_id=1 ";

			MySql.Data.MySqlClient.MySqlDataReader rea = kt.Db.ExecuteQuery(query);
			while (rea.Read())
			{
				ListItem current = new ListItem(rea["name"].ToString(), rea["idi"].ToString());
				lista.Items.Add(current);
			}
			rea.Close();

			string indi = System.Web.HttpContext.Current.Server.MapPath("logShowDocuments.txt");
			FileInfo tlog = new FileInfo(indi);
			StreamWriter scrivi = tlog.CreateText();
			scrivi.WriteLine(query);
			scrivi.Close();
			
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.delete.Click += new System.EventHandler(this.delete_Click);
			this.gotoBasket.Click += new System.EventHandler(this.gotoBasket_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion
		
		DataTable getGrid(string document)
		{
			DataTable dt = new DataTable();
			dt.Columns.Add(new DataColumn("id"));
			dt.Columns["id"].DataType = System.Type.GetType("System.String");
			dt.Columns.Add(new DataColumn("name"));
			dt.Columns["name"].DataType = System.Type.GetType("System.String");
			dt.Columns.Add(new DataColumn("versionid"));
			dt.Columns["versionid"].DataType = System.Type.GetType("System.String");
			dt.Columns.Add(new DataColumn("date"));
			dt.Columns["date"].DataType = System.Type.GetType("System.String");
			dt.Columns.Add(new DataColumn("owner"));
			dt.Columns["owner"].DataType = System.Type.GetType("System.String");

			string query = "select document_content_version.document_id, document_content_version.filename, document_metadata_version.version_created, "+
				" document_metadata_version.version_creator_id, document_metadata_version.name as docname, users.name as username"+
				" from document_content_version join document_metadata_version  "+
				" on (document_content_version.id = document_metadata_version.content_version_id) "+
				" join users on (users.id = document_metadata_version.version_creator_id) "+
				" where document_content_version.document_id="+document+
				" order by document_content_version.id";
			MySql.Data.MySqlClient.MySqlDataReader rea = kt.Db.ExecuteQuery(query);
			int contatore = 1;
			string ktfsWeb = System.Configuration.ConfigurationSettings.AppSettings["ktfsWeb"].ToString();
			while (rea.Read())
			{
				DataRow riga = dt.NewRow();
				string filename = rea["filename"].ToString();
				string docname = rea["docname"].ToString();
				riga[0] = rea["document_id"].ToString();
				//url sulla MIA macchina
				string url = "<a href=\""+ktfsWeb+filename+"\">"+docname+"</a>";
				//url all'esterno su services
				riga[1] = replaceUrl(url); 
				riga[2] = contatore.ToString();
				contatore++;
				riga[3] = rea["version_created"].ToString();
				riga[4] = rea["username"].ToString();
				dt.Rows.Add(riga);
			}
			rea.Close();
			kt.Db.CloseConnection();

			return dt;
		}

		/*
		private void prova_Click(object sender, System.EventArgs e)
		{
			//chiamo il ws all'esterno e vedo se mi ritorna l'url giusto
			it.txt.services.documentManagement docman = new Kt.it.txt.services.documentManagement();
			string stampa = docman.getVersion(1, 0);
			eti.Text = "Risultato della chiamata: "+stampa;
		}
		*/

		private string replaceUrl(string url)
		{
			string extName = System.Configuration.ConfigurationSettings.AppSettings["serverExtName"].ToString();
			string intName = System.Configuration.ConfigurationSettings.AppSettings["serverIntName"].ToString();
			string ris = url.Replace(intName, extName);
			return ris;
		}

		private void delete_Click(object sender, System.EventArgs e)
		{
			/*problema: se chiamo il mio ws non ho lo username da passargli
			chiamo la procedura interna (senza gestione errori)
			*/
			kt.deleteKtDocument(lista.SelectedItem.Value);
			feedback.Text = traduzione.getText("deleted");
			
			try
			{
				lista.Items.Clear();
				showDocuments();
				
				DataTable emptydt = new DataTable();
				emptydt.Columns.Add(new DataColumn("id"));
				emptydt.Columns["id"].DataType = System.Type.GetType("System.String");
				emptydt.Columns.Add(new DataColumn("name"));
				emptydt.Columns["name"].DataType = System.Type.GetType("System.String");
				emptydt.Columns.Add(new DataColumn("versionid"));
				emptydt.Columns["versionid"].DataType = System.Type.GetType("System.String");
				emptydt.Columns.Add(new DataColumn("date"));
				emptydt.Columns["date"].DataType = System.Type.GetType("System.String");
				emptydt.Columns.Add(new DataColumn("owner"));
				emptydt.Columns["owner"].DataType = System.Type.GetType("System.String");
				datagrid.DataSource = emptydt;
				datagrid.DataBind();

			}
			catch (Exception ex)
			{
				string ecc = ex.Message;
			}
		}

		private void gotoBasket_Click(object sender, System.EventArgs e)
		{
			Response.Redirect("basket.aspx", false);
		}



	}
}
